package rs.udd.service;

import javax.annotation.Resource;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import rs.udd.model.Admin;
import rs.udd.model.Advertiser;
import rs.udd.model.Agent;
import rs.udd.repository.AdminRepository;
import rs.udd.repository.AdvertiserRepository;
import rs.udd.repository.AgentRepository;

@Service
@Transactional
public class UserServiceImpl implements UserService {

	private static final Logger LOGGER = LogManager.getLogger(UserServiceImpl.class);

	@Resource
	private AdminRepository adminRepository;

	@Resource
	private AgentRepository agentRepository;

	@Resource
	private AdvertiserRepository advertiserRepository;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

		LOGGER.info("Looking for user with '" + username + "' username...");

		Admin admin = adminRepository.findByUsername(username);
		if (admin != null) {
			LOGGER.info("User found: " + admin);
			return admin;
		}

		Agent agent = agentRepository.findByUsername(username);
		if (agent != null) {
			LOGGER.info("User found: " + agent);
			return agent;
		}

		Advertiser advertiser = advertiserRepository.findByUsername(username);
		if (advertiser != null) {
			LOGGER.info("User found: " + advertiser);
			if (advertiser.getActive() && advertiser.getEmailActive())
				return advertiser;
			else
				throw new UsernameNotFoundException("Advertiser '" + advertiser.getUsername() + "' didn't activated email.");
		}

		LOGGER.error("User with username '" + username + "' not found");
		throw new UsernameNotFoundException("User with '" + username + "' does not exist.");
	}
}
